//
//  ViewController.m
//  弹幕播放器
//
//  Created by 煜张 on 2018/10/17.
//  Copyright © 2018 煜张. All rights reserved.
//

#import "ViewController.h"
#import "AFNetworking.h"
@interface ViewController ()
@property (nonatomic,strong)NSMutableArray * danmuList;
@property (nonatomic,strong)dispatch_source_t playTimer;
@property (nonatomic,assign)NSInteger time;
@property (nonatomic,strong)UIVisualEffectView * effectView;
@property (nonatomic,strong)UITextField * textField;
@property (nonatomic,strong)AFHTTPSessionManager * manager;
@property (nonatomic,strong)UISlider * slider;
@property (nonatomic,strong)UILabel * currentTimeLabel;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[UIApplication sharedApplication] setIdleTimerDisabled: YES];
    [UIApplication sharedApplication].statusBarHidden = YES;
    self.view.backgroundColor = [UIColor blackColor];
    self.danmuList = [NSMutableArray new];
    self.manager = [AFHTTPSessionManager manager];
    //设置界面
    UITapGestureRecognizer * a = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showSettingView)];
    [self.view addGestureRecognizer:a];
    a.numberOfTapsRequired = 3;
    a.requiresExclusiveTouchType = YES;
    self.effectView = [[UIVisualEffectView alloc]initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    self.effectView.frame = self.view.frame;
    self.effectView.hidden = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication].keyWindow addSubview:self.effectView];
    });
    
    UITapGestureRecognizer * b = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showSettingView)];
    [self.effectView addGestureRecognizer:b];
    b.requiresExclusiveTouchType = YES;
    CGSize inputSize = CGSizeMake(300, 40);
    self.textField = [[UITextField alloc]initWithFrame:CGRectMake((self.view.bounds.size.width-inputSize.width)/2, (self.view.bounds.size.height-inputSize.height)/3, inputSize.width, inputSize.height)];
    self.textField.placeholder = @"优酷播放网页检查搜索\"videoId\"";
    [self.effectView.contentView addSubview:self.textField];
    self.textField.borderStyle = UITextBorderStyleRoundedRect;
    self.textField.keyboardType = UIKeyboardTypeNumberPad;
    [self.textField becomeFirstResponder];
    
    
    
    self.currentTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(20, CGRectGetMaxY(self.textField.frame)+15, 60, 50)];
    self.currentTimeLabel.textColor = [UIColor whiteColor];
    self.currentTimeLabel.font = [UIFont boldSystemFontOfSize:12];
    [self.effectView.contentView addSubview:self.currentTimeLabel];
    
    self.slider = [[UISlider alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.currentTimeLabel.frame), CGRectGetMaxY(self.textField.frame)+14, self.view.bounds.size.width-140, 20)];
    self.slider.minimumValue = 0;
    self.slider.maximumValue = 4000;
    [self.slider addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
    [self.slider addTarget:self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpOutside|UIControlEventTouchUpInside];
    [self.slider addTarget:self action:@selector(touchDown:) forControlEvents:UIControlEventTouchDown];
    [self.effectView.contentView addSubview:self.slider];
}
- (void)touchDown:(UISlider *)slider{
    if(self.danmuList.count)dispatch_suspend(self.playTimer);
}
- (void)valueChange:(UISlider *)slider{
    self.currentTimeLabel.text = [self getMMSSFromSS:lroundf(slider.value)];
}
- (void)touchUp:(UISlider *)slider{
    self.time = lroundf(slider.value);
    if(self.danmuList.count)dispatch_resume(self.playTimer);
}
- (void)getDate{
    [self.danmuList removeAllObjects];
    for (int i = 0; i < 100; i++)
    {
        [self.manager GET:[NSString stringWithFormat:@"https://service.danmu.youku.com/list?mat=%d&iid=%@&ct=1001",i,self.textField.text] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([[responseObject objectForKey:@"count"]integerValue]!=0) {
                for (id obj in [responseObject objectForKey:@"result"]) {
                    NSDictionary * danmu = @{@"content":[obj objectForKey:@"content"],@"playat":[obj objectForKey:@"playat"]};
                    [self.danmuList addObject:danmu];
                }
            }
            if (i==99) {
                [self starTime];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}
- (void)starTime{
    self.time = 0;
    self.textField.text = @"";
    self.playTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(self.playTimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(self.playTimer, ^{
        
        for (int i = 0; i<self.danmuList.count; i++) {
            NSInteger time = (NSInteger)[[self.danmuList[i] objectForKey:@"playat"] integerValue];
            if (time/1000==self.time) {
                [self createDanmu:[self.danmuList[i] objectForKey:@"content"]];
                [self.danmuList removeObjectAtIndex:i];
            }
        }
        if (!self.effectView.hidden) {
            self.slider.value = self.time;
            self.currentTimeLabel.text = [self getMMSSFromSS:self.time];
        }
        self.time++;
    });
    dispatch_resume(self.playTimer);
}
-(NSString *)getMMSSFromSS:(NSInteger)seconds{
    //format of hour
    NSString *str_hour = [NSString stringWithFormat:@"%02ld",seconds/3600];
    //format of minute
    NSString *str_minute = [NSString stringWithFormat:@"%02ld",(seconds%3600)/60];
    //format of second
    NSString *str_second = [NSString stringWithFormat:@"%02ld",seconds%60];
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@:%@",str_hour,str_minute,str_second];
    return format_time;
}

- (void)showSettingView{
    self.effectView.hidden = !self.effectView.hidden;
    if (self.effectView.hidden&&![self.textField.text isEqualToString:@""]) {
        //31969285
        [self getDate];
    }
    [self.textField resignFirstResponder];
}

- (void)createDanmu:(NSString *)string{
    CGFloat width = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, 50)
                                         options:NSStringDrawingUsesLineFragmentOrigin
                                      attributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:35]}
                                         context:nil].size.width;
    UILabel * label =[[UILabel alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width, arc4random()%325, width, 50)];
    label.shadowColor =[UIColor blackColor];
    label.text = string;
    label.textColor = [UIColor colorWithRed:(arc4random()%155+100)/255.0 green:(arc4random()%155+100)/255.0 blue:(arc4random()%155+100)/255.0 alpha:1];
    label.font = [UIFont boldSystemFontOfSize:35];
    [self.view addSubview:label];
    
    [UIView animateWithDuration:7 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
        CGRect temp = label.frame;
        temp = CGRectMake(-width, label.frame.origin.y, width, 50);
        label.frame = temp;
    } completion:^(BOOL finished) {
        [label removeFromSuperview];
    }];
}
@end
